﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Newtonsoft.Json;

namespace RedmineHelper
{
    public partial class FormMain : Form
    {
        public FormMain()
        {
            InitializeComponent();
        }

        private allissues issues;
        private allprojects projects;
        private account currentAccount;
        private project currentProject;
        private int currentPage = 0, limit = 25, total = 0;
        private void FormMain_Load(object sender, EventArgs e)
        {
            LoadAccounts();
        }
        void LoadAccounts()
        {
            for (int i = 2; i < systemToolStripMenuItem.DropDownItems.Count;i++ )
            {
                    systemToolStripMenuItem.DropDownItems.RemoveAt(i);
            }

            IList<account> accounts = AccountHelper.LoadAccounts();
            foreach (var a in accounts)
            {
                ToolStripMenuItem menu = new ToolStripMenuItem(a.host, null, null, a.host);
                menu.Tag = a.host;
                menu.Click += new EventHandler(account_Click);
                systemToolStripMenuItem.DropDownItems.Add(menu);
            }
            if(accounts.Count>0)
            {
                account_Click(systemToolStripMenuItem.DropDownItems[2],null);
            }
        }

        void account_Click(object sender, EventArgs e)
        {
            for (int i = 2; i < systemToolStripMenuItem.DropDownItems.Count; i++)
            {
                ((ToolStripMenuItem)systemToolStripMenuItem.DropDownItems[i]).Checked = false;
            }

            ToolStripMenuItem menu = (ToolStripMenuItem)sender;
            menu.Checked = true;
            IList<account> accounts = AccountHelper.LoadAccounts();
            var all = from a in accounts where a.host == menu.Tag.ToString() select a;
            if(all.Count()>0)
                LoadProjects(all.First());
        }

        void project_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem menu = (ToolStripMenuItem)sender;
            menu.Checked = true;
            var ps = from p in projects.projects where p.id == (int)menu.Tag select p;
            currentProject = ps.First();
            LoadIssues();
        }

        private void LoadProjects(account a)
        {
            currentAccount = a;
            projectsToolStripMenuItem.DropDownItems.Clear();
            lst.Items.Clear();
            string json = HttpHelper.GetUrlContent("http://" + currentAccount.host + "/projects.json", UrlMethod.GET,
                                                   Encoding.UTF8,
                                                   UserAgent.IE, "", "", currentAccount);
            projects = JsonConvert.DeserializeObject<allprojects>(json);
            foreach (var project in projects.projects)
            {
                ToolStripMenuItem menu = new ToolStripMenuItem(project.name, null, null, project.id.ToString());
                menu.Tag = project.id;
                menu.Click += new EventHandler(project_Click);
                projectsToolStripMenuItem.DropDownItems.Add(menu);
            }
            if (projects.projects.Count == 1)
            {
                currentProject = projects.projects[0];
                LoadIssues();
                ToolStripMenuItem menu = (ToolStripMenuItem)projectsToolStripMenuItem.DropDownItems[0];
                menu.Checked = true;
            }
        }

        private void LoadIssues()
        {
            string json =
                HttpHelper.GetUrlContent(
                    string.Format("http://{0}/issues.json?project_id={1}&offset={2}&limit={3}", currentAccount.host,
                                  currentProject.id, currentPage*limit, limit), UrlMethod.GET, Encoding.UTF8,
                    UserAgent.IE, "", "", currentAccount);
            issues = JsonConvert.DeserializeObject<allissues>(json);
            lst.Items.Clear();
            foreach (var issue in issues.issues)
            {
                ListViewItem item = new ListViewItem(issue.id.ToString());
                item.SubItems.Add(issue.subject);
                item.SubItems.Add(issue.status.name);
                item.SubItems.Add(issue.priority.name);
                item.SubItems.Add(issue.created_on.ToString());
                lst.Items.Add(item);
            }
            total = issues.total_count;
            issuesToolStripMenuItem.Text = "Issues(" + total + ")";
            firstPageToolStripMenuItem.Enabled = (currentPage > 0);
            prevPageToolStripMenuItem.Enabled = (currentPage > 0);
            nextPageToolStripMenuItem.Enabled = ((currentPage + 1) * limit < total);
            lastPageToolStripMenuItem.Enabled = ((currentPage + 1) * limit < total);
        }

        private void closeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if(lst.SelectedIndices.Count>0)
            {
                ListViewItem item = lst.SelectedItems[0];
                string id = item.Text;
                string result = HttpHelper.GetUrlContent("http://" + currentAccount.host + "/issues/" + id + ".json", UrlMethod.PUT, Encoding.UTF8,
                                         UserAgent.IE, "{\"issue\": {\"status_id\": "+currentAccount.closeid+"}}", "", currentAccount);
                lst.Items.Remove(item);
                total--;
                issuesToolStripMenuItem.Text = "Issues(" + total + ")";
            }
        }

        private void lst_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lst.SelectedIndices.Count > 0)
            {
                ListViewItem item = lst.SelectedItems[0];
                string id = item.Text;
                var list = from i in issues.issues where i.id == int.Parse(id) select i;
                if (list.Count() > 0)
                    txt.Text = list.First().description;
            }
        }

        private void accountsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FormAccounts fa = new FormAccounts();
            fa.ShowDialog();
            fa.Close();
            LoadAccounts();
        }

        private void reloadToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LoadIssues();
        }

        private void firstPageToolStripMenuItem_Click(object sender, EventArgs e)
        {
            currentPage = 0;
            LoadIssues();
        }

        private void prevPageToolStripMenuItem_Click(object sender, EventArgs e)
        {
            currentPage--;
            LoadIssues();
        }

        private void nextPageToolStripMenuItem_Click(object sender, EventArgs e)
        {
            currentPage++;
            LoadIssues();
        }

        private void lastPageToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (total % 25 == 0)
                currentPage = total/25 - 1;
            else
                currentPage = total / 25;
            LoadIssues();
        }

        private void FormMain_SizeChanged(object sender, EventArgs e)
        {
            if(this.WindowState==FormWindowState.Minimized)
            {
                this.ShowInTaskbar = false;
            }
        }

        private void notifyIcon_Click(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
                this.WindowState = FormWindowState.Normal;
            this.Activate();
            this.ShowInTaskbar = true; 
        }
    }
}
